package com.lxq.live.dao;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lxq.live.pojo.VerificationCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.time.Duration;

@Component
public class RedisVerificationCode{
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    public boolean create(VerificationCode verificationCode){
        if (isExist(verificationCode.getUserId())!=null){
            return false;
        }
        ValueOperations<String, String> restVO=stringRedisTemplate.opsForValue();
        var series=new Gson().toJson(verificationCode);
        restVO.set("reset_password_"+verificationCode.getUserId(),series, Duration.ofHours(24));
        return true;
    }
    public boolean update(VerificationCode verificationCode){
        if (isExist(verificationCode.getUserId())==null){
            return false;
        }
        ValueOperations<String, String> restVO=stringRedisTemplate.opsForValue();
        var series=new Gson().toJson(verificationCode);
        restVO.set("reset_password_"+verificationCode.getUserId(),series);
        return true;
    }
    public VerificationCode isExist(String userId){
        ValueOperations<String, String> restVO=stringRedisTemplate.opsForValue();
        var series=restVO.get("reset_password_"+userId);
        if (series==null)return null;
        if (series.equals(""))return null;
        var verificationCode= new Gson().fromJson(series,new TypeToken<VerificationCode>(){}.getType());
        return (VerificationCode) verificationCode;
    }

}
